<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/27
 * Time: 18:05
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use zhtfrontend\modules\sitepadapi\components\rest\ActivebackController;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class CategoryController extends ActivebackController
{
    public $modelClass = 'common\models\datas\Category';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionCourseindex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['parent_id'=>0,'module' => 'course']);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }
    public function actionProductindex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['parent_id'=>0,'module' => 'product']);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionView($id)
    {
        return $this->findModel($id);
    }

        public function actionFindbycpid($parent_id)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['parent_id'=>$parent_id,'module'=>'course']);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionFindbyppid($parent_id)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['parent_id'=>$parent_id,'module'=>'product']);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }


    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne($id);
        if ($model !== null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }
}